package bookmanage;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.Callable;

public class UserDao {
    // 主要实现一个根据用户名找密码的逻辑即可
    // 此处我们希望用户名是唯一的 查找到的结果只有0条或1条
    public User selectByName(String name){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "select * from user where username =?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,name);
            resultSet = statement.executeQuery();
            if (resultSet.next()){
                // 存在
                boolean isAdmin = (resultSet.getInt("isAdmin")==1);
                User user = null;
                if (isAdmin){
                    user = new Admin();
                }else {
                    user = new NormalUser();
                }
                user.setUserId(resultSet.getInt("userId"));
                user.setName(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,resultSet  );
        }
        return null;
    }
}
